using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using NAnt.Core;
using NAnt.Core.Attributes;
using NAnt.Core.Tasks;
using NAnt.Core.Util;

[TaskName("forproperties")]
public class ForPropertiesTask : TaskContainer
{
	private string nameProperty;
	private string valueProperty;
	private string pattern;
	private string capture;

	[TaskAttribute("nameProperty", Required = false), StringValidator(AllowEmpty = false)]
	public string NameProperty
	{
		get { return nameProperty; }
		set { nameProperty = value; }
	}

	[TaskAttribute("valueProperty", Required = false), StringValidator(AllowEmpty = false)]
	public string ValueProperty
	{
		get { return valueProperty; }
		set { valueProperty = value; }
	}

	[TaskAttribute("pattern", Required = true), StringValidator(AllowEmpty = false)]
	public string Pattern
	{
		get { return pattern; }
		set { pattern = value; }
	}

	[TaskAttribute("capture", Required = false), StringValidator(AllowEmpty = false)]
	public string Capture
	{
		get { return capture; }
		set { capture = value; }
	}

	private TaskContainer stuffToDo;

	[BuildElement("do")]
	public TaskContainer StuffToDo
	{
		get { return stuffToDo; }
		set { stuffToDo = value; }
	}

	protected override void ExecuteTask()
	{
		List<DictionaryEntry> selectedProperties = GetSelectedProperties();

		foreach (DictionaryEntry dictionaryEntry in selectedProperties)
		{
			string propertyName = dictionaryEntry.Key.ToString();
			if (!string.IsNullOrEmpty(NameProperty))
				Properties[NameProperty] = propertyName;

			if (!string.IsNullOrEmpty(ValueProperty))
				Properties[ValueProperty] = dictionaryEntry.Value.ToString();
			if (!string.IsNullOrEmpty(Capture))
			{
				Match match = Regex.Match(propertyName, Pattern);
				Properties[Capture] = match.Groups[1].Value;
			}

			base.ExecuteTask();
		}
	}

	private List<DictionaryEntry> GetSelectedProperties()
	{
		List<DictionaryEntry> selectedProperties = new List<DictionaryEntry>(); 
		foreach (DictionaryEntry dictionaryEntry in Project.Properties)
			if (Regex.IsMatch(dictionaryEntry.Key.ToString(), Pattern))
				selectedProperties.Add(dictionaryEntry);
		return selectedProperties;
	}
}